package com.example.auv_660.network.tcp;

import com.example.auv_660.moduleload.ModuleLoad;

import java.io.IOException;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.ArrayList;

public class ModuleConnHandler implements CompletionHandler<AsynchronousSocketChannel, ModuleConnHandler> {

    @Override
    public void completed(AsynchronousSocketChannel connChannel, ModuleConnHandler connHandler) {
        String remoteModuleIP = null;

        try {
            String remoteAdr = connChannel.getRemoteAddress().toString();
            int ipEndPosition = remoteAdr.indexOf(":");
            remoteModuleIP = remoteAdr.substring(1, ipEndPosition);

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("I get a remoteModuleIP: " + remoteModuleIP);
        ArrayList<ModuleLoad> instatces = HFTCPBuild.INSTANCE.getModuleInstance();
        if (instatces.size() != 0) {
            instatces.get(0).doModuleLoad(remoteModuleIP, connChannel);
        }

        AsynchronousServerSocketChannel asynchronousServerSocketChannel
                = HFTCPBuild.INSTANCE.getHFTcpServer().getAsynchronousServerSocketChannel();
        if (asynchronousServerSocketChannel != null) {
            asynchronousServerSocketChannel.accept(this, this);
        }
    }

    @Override
    public void failed(Throwable throwable, ModuleConnHandler connHandler) {
        throwable.printStackTrace();
    }

}
